package com.iteaj.iboot.module.iot.collect.messageParsing.modbus;

import static ch.qos.logback.core.encoder.ByteArrayUtil.hexStringToByteArray;


public class ModbusRtuHelper {

    public static void parseModbusRtu(String message) {
        // 将Modbus RTU报文字符串转换为字节数组
        byte[] modbusFrame = hexStringToByteArray(message);
        // 验证报文长度是否符合预期
//        if (modbusFrame.length < 3  + 2 ) {
//            System.out.println("Invalid Modbus RTU frame length");
//            return;
//        }
        if(message.length()<=8){
            System.out.println("Invalid Modbus RTU frame length");
            return;
        }

//        // 读取地址字段
//        System.out.println(Integer.parseInt(message.substring(0,2)));
        int address =Integer.parseInt(message.substring(0,2));
        System.out.println("address:"+address);

        // 读取功能码
        int functionCode =Integer.parseInt(message.substring(2,4));
        System.out.println("功能码:"+functionCode);

        // 读取数据字段长度
        int dataLength = Integer.parseInt(message.substring(4,6));
        System.out.println("数据长度:"+dataLength);
//
//        System.out.println(message.length()-8);
        // 验证报文长度是否符合预期
        if (message.length()-8 < dataLength*2 ) {
            System.out.println("Invalid Modbus RTU frame length");
            return;
        }

        // 读取数据字段
//        byte[] data = new byte[dataLength];
//        int idx=6;
        String dataStr = message.substring(6, 6 + dataLength * 2);
        System.out.println(dataStr);
//        System.out.println(message.substring(6+dataLength*2,message.length()));
//        for(int i=0;i<dataLength;i++){
//            data[i]=(byte) Integer.parseInt(message.substring(idx,idx+2),16);
//            idx+=2;
//            System.out.println(data[i]);
//        }

        // 读取CRC校验码
        String crc = message.substring(6+dataLength*2,message.length());

        // 执行CRC校验
//        if (!validateCRC(message, 6+dataLength*2, message.length()-(6+dataLength*2), crc)) {
//            System.out.println("CRC validation failed");
//            return;
//        }

        // 在这里进行根据功能码处理数据的逻辑
        processModbusData(address, functionCode, dataStr);
    }

    //验证CRC
    public static boolean validateCRC(String msg, int offset, int length, String crcValue) {
        int calculatedCRC = calculateCRC(msg, offset, length);
        // 解析 crcValue 字符串为整数
        int parsedCRC = Integer.parseInt(crcValue, 16);
        return (calculatedCRC & 0xFFFF) == (parsedCRC & 0xFFFF);
    }


    public static int calculateCRC(String msg, int offset, int length) {
        int crc = 0xFFFF;
        for (int i = offset; i < offset + length; i++) {
            crc ^= msg.charAt(i) & 0xFF;
            for (int j = 0; j < 8; j++) {
                if ((crc & 0x0001) != 0) {
                    crc = (crc >> 1) ^ 0xA001;
                } else {
                    crc = crc >> 1;
                }
            }
        }
        return crc;
    }


    private static void processModbusData(int address, int functionCode, String data) {
        float f=Float.parseFloat(data);
        // 在这里根据功能码处理数据，你可以根据实际需求进行相应的业务逻辑
        System.out.println("Address: " + address);
        System.out.println("Function Code: " + functionCode);
        System.out.println("Data: " + data);
        System.out.println("Parse Data:"+f);
    }

    private static String byteArrayToHexString(byte[] byteArray) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : byteArray) {
            hexString.append(String.format("%02X", b));
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        String modbusFrame = "100304025E00915AF4";
        byte[] bytes=modbusFrame.getBytes();
        for(int i=0;i<bytes.length;i++){
            System.out.printf("%02x \n",bytes[i]);
        }
        // 解析Modbus RTU报文
        parseModbusRtu(modbusFrame);
    }
}
